/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 */
package com.opensymphony.user.provider.hibernate3.ahxu.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.SQLException;


/**
 * @author <a href="mailto:matthew@linjafoo.com">Matthew E. Porter</a>
 */
public class SessionManager {
    //~ Static fields/initializers /////////////////////////////////////////////

    private static Log log = LogFactory.getLog(SessionManager.class.getName());

    //~ Instance fields ////////////////////////////////////////////////////////

    private SessionFactory sessionFactory;

    //~ Constructors ///////////////////////////////////////////////////////////

    public SessionManager(Configuration configuration) throws HibernateException {
        try {
            this.sessionFactory = configuration.buildSessionFactory();
        } catch (HibernateException he) {
            log.error("Problem creating SessionFactory.", he);
            throw he;
        }
    }

    public SessionManager(SessionFactory sessionFactory) throws HibernateException {
        this.sessionFactory = sessionFactory;
    }

    //~ Methods ////////////////////////////////////////////////////////////////

    public Session getSession() throws HibernateException {
        Session session = null;

        try {
            session = this.sessionFactory.openSession();
        } catch (HibernateException he) {
            log.error("Problem obtaining a session", he);
        }

        return session;
    }

    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }

    public void closeSession(Session session) {
        try {
            session.flush();
            session.close();
        } catch (HibernateException he) {
            if (log.isDebugEnabled()) {
                log.debug("HibernateException caught closing connection.");
            }
        }
    }

    public void flushCloseSession(Session session) {
        try {
            session.flush();

            if (!session.connection().getAutoCommit()) {
                session.connection().commit();
            }

            this.closeSession(session);
        } catch (HibernateException he) {
            if (log.isDebugEnabled()) {
                log.debug("HibernateException caught during flush/commit.", he);
            }
        } catch (SQLException sqle) {
            if (log.isDebugEnabled()) {
                log.debug("SQLException caught during commit.", sqle);
            }
        }
    }
}
